示例概述#
本节将通过几个完整的示例来展示如何开发不同类型的 Skills。这些示例涵盖了常见的使用场景,可以作为开发自己 Skills 的参考。
示例 1:文本处理 Skill#
1.1 Skill 定义#
python
1.2 使用示例#
python
示例 2:代码生成 Skill#
2.1 Skill 定义#
src/skills/code_generator.py
from typing import Dict, Any from claude_code_sdk import Skill, SkillContext, SkillResult class CodeGeneratorSkill(Skill): """代码生成 Skill""" def init(self): super().init( name="code-generator", version="1.0.0", description="Generate code from specifications" ) def get_parameters_schema(self) -> Dict[str, Any]: return { "type": "object", "properties": { "language": { "type": "string", "enum": ["python", "javascript", "java", "go"], "description": "Programming language" }, "type": { "type": "string", "enum": ["function", "class", "interface", "enum"], "description": "Code type to generate" }, "name": { "type": "string", "description": "Name of the function/class" }, "description": { "type": "string", "description": "Description of what the code should do" }, "parameters": { "type": "array", "description": "List of parameters", "items": { "type": "object", "properties": { "name": {"type": "string"}, "type": {"type": "string"}, "default": {"type": "string"} } } }, "return_type": { "type": "string", "description": "Return type" } }, "required": ["language", "type", "name", "description"] } def execute(self, parameters: Dict[str, Any], context: SkillContext) -> SkillResult: try: language = parameters["language"] code_type = parameters["type"] name = parameters["name"] description = parameters["description"] params = parameters.get("parameters", []) return_type = parameters.get("return_type", "void")
生成代码
code = self.generate_code( language, code_type, name, description, params, return_type ) return SkillResult( success=True, data={ "language": language, "type": code_type, "name": name, "code": code, "description": description } ) except Exception as e: return SkillResult( success=False, error=str(e) ) def generate_code(self, language: str, code_type: str, name: str, description: str, params: list, return_type: str) -> str: """生成代码""" generators = { "python": self.generate_python, "javascript": self.generate_javascript, "java": self.generate_java, "go": self.generate_go } generator = generators.get(language) if not generator: raise ValueError(f"Unsupported language: {language}") return generator(code_type, name, description, params, return_type) def generate_python(self, code_type: str, name: str, description: str, params: list, return_type: str) -> str: """生成 Python 代码""" param_str = ", ".join([f"{p['name']}: {p['type']}" for p in params]) if code_type == "function": code = f'''def {name}({param_str}) -> {return_type}: """ {description} """ pass ''' elif code_type == "class": code = f'''class {name}: """ {description} """ def init(self{self._init_params(params)}): pass ''' else: raise ValueError(f"Unsupported code type: {code_type}") return code def generate_javascript(self, code_type: str, name: str, description: str, params: list, return_type: str) -> str: """生成 JavaScript 代码""" param_str = ", ".join([f"{p['name']}" for p in params]) if code_type == "function": code = f'''/**
- {description}
- @param {param_str}
- @returns {{{return_type}}} / function {name}({param_str}) {{ // TODO: implement }} ''' elif code_type == "class": code = f'''/*
- {description} / class {name} {{ constructor({param_str}) {{ // TODO: implement }} }} ''' else: raise ValueError(f"Unsupported code type: {code_type}") return code def generate_java(self, code_type: str, name: str, description: str, params: list, return_type: str) -> str: """生成 Java 代码""" param_str = ", ".join([f"{p['type']} {p['name']}" for p in params]) if code_type == "function": code = f'''/*
- {description} / public {return_type} {name}({param_str}) {{ // TODO: implement return null; }} ''' elif code_type == "class": code = f'''/*
- {description} */ public class {name} {{ public {name}({param_str}) {{ // TODO: implement }} }} ''' else: raise ValueError(f"Unsupported code type: {code_type}") return code def generate_go(self, code_type: str, name: str, description: str, params: list, return_type: str) -> str: """生成 Go 代码""" param_str = ", ".join([f"{p['name']} {p['type']}" for p in params]) if code_type == "function": code = f'''// {description} func {name}({param_str}) {return_type} {{ // TODO: implement return }} ''' elif code_type == "class": code = f'''// {description} type {name} struct {{ // TODO: add fields }} // New{Name} creates a new {name} func New{name}({param_str}) *{name} {{ return &{name}{{ // TODO: initialize fields }} }} ''' else: raise ValueError(f"Unsupported code type: {code_type}") return code def _init_params(self, params: list) -> str: """生成初始化参数""" if not params: return "" return ", " + ", ".join([p["name"] for p in params])
bash
3.2 使用示例#
python
print(result.data)
示例 2:分析目录
result = skill.execute( { "path": "src", "analysis_type": "size", "recursive": True }, context )
print(f"Total size: {result.data['total_size']} bytes")
示例 3:分析特定文件类型
result = skill.execute( { "path": "src", "analysis_type": "structure", "recursive": True, "include_patterns": [".py"], "exclude_patterns": ["pycache", ".pyc"] }, context )
print(f"Python files found: {result.data['file_count']}")
示例 4:测试生成 Skill#
4.1 Skill 定义#
src/skills/test_generator.py
from typing import Dict, Any from claude_code_sdk import Skill, SkillContext, SkillResult class TestGeneratorSkill(Skill): """测试生成 Skill""" def init(self): super().init(
name="test-generator", version="1.0.0", description="Generate unit tests from code" ) def get_parameters_schema(self) -> Dict[str, Any]: return { "type": "object", "properties": { "file_path": { "type": "string", "description": "Path to the source file" }, "test_framework": { "type": "string", "enum": ["pytest", "unittest", "jest"], "description": "Test framework to use" }, "include_edge_cases": { "type": "boolean", "description": "Include edge case tests", "default": True }, "include_mocks": { "type": "boolean", "description": "Include mock objects", "default": False } }, "required": ["file_path"] } def execute(self, parameters: Dict[str, Any], context: SkillContext) -> SkillResult: try: file_path = parameters["file_path"] test_framework = parameters.get("test_framework", "pytest") include_edge_cases = parameters.get("include_edge_cases", True) include_mocks = parameters.get("include_mocks", False)
读取源文件
source_code = context.read_file(file_path)
分析代码
functions = self.analyze_functions(source_code)
生成测试
test_code = self.generate_tests( file_path, functions, test_framework, include_edge_cases, include_mocks ) return SkillResult( success=True, data={ "source_file": file_path, "test_framework": test_framework, "functions_tested": len(functions), "test_code": test_code } ) except Exception as e: return SkillResult( success=False, error=str(e) ) def analyze_functions(self, source_code: str) -> list: """分析源代码中的函数""" import re functions = [] pattern = r'def\s+(\w+)\s*(([^)]*)):' for match in re.finditer(pattern, source_code): function_name = match.group(1) params = match.group(2).strip() functions.append({ "name": function_name, "params": [p.strip() for p in params.split(',') if p.strip()] }) return functions def generate_tests(self, file_path: str, functions: list, test_framework: str, include_edge_cases: bool, include_mocks: bool) -> str: """生成测试代码""" generators = { "pytest": self.generate_pytest, "unittest": self.generate_unittest, "jest": self.generate_jest } generator = generators.get(test_framework) if not generator: raise ValueError(f"Unsupported test framework: {test_framework}") return generator(file_path, functions, include_edge_cases, include_mocks) def generate_pytest(self, file_path: str, functions: list, include_edge_cases: bool, include_mocks: bool) -> str: """生成 pytest 测试""" import os module_name = os.path.splitext(os.path.basename(file_path))[0] test_code = f'''import pytest from {module_name} import {', '.join([f['name'] for f in functions])} ''' for func in functions: test_code += f'''class Test{func['name'].capitalize()}: """Test cases for {func['name']}""" def test_{func['name']}_basic(self): """Basic test for {func['name']}"""
TODO: implement test
pass ''' if include_edge_cases: test_code += f''' def test_{func['name']}_edge_cases(self): """Edge case tests for {func['name']}"""
TODO: implement edge case tests
pass ''' if include_mocks: test_code += f''' def test_{func['name']}_with_mocks(self): """Test {func['name']} with mocks"""
TODO: implement tests with mocks
pass ''' return test_code def generate_unittest(self, file_path: str, functions: list, include_edge_cases: bool, include_mocks: bool) -> str: """生成 unittest 测试""" import os module_name = os.path.splitext(os.path.basename(file_path))[0] test_code = f'''import unittest from {module_name} import {', '.join([f['name'] for f in functions])} class Test{module_name.capitalize()}(unittest.TestCase): """Test cases for {module_name}""" ''' for func in functions: test_code += f''' def test_{func['name']}(self): """Test {func['name']}"""
TODO: implement test
pass ''' if include_edge_cases: test_code += f''' def test_{func['name']}_edge_cases(self): """Test {func['name']} edge cases"""
TODO: implement edge case tests
pass ''' test_code += ''' if name == 'main': unittest.main() ''' return test_code def generate_jest(self, file_path: str, functions: list, include_edge_cases: bool, include_mocks: bool) -> str: """生成 Jest 测试""" import os module_name = os.path.splitext(os.path.basename(file_path))[0] test_code = f'''const {{ {', '.join([f['name'] for f in functions])} }} = require('./{module_name}'); ''' for func in functions: test_code += f'''describe('{func['name']}', () => {{ test('basic test', () => {{ // TODO: implement test }}); ''' if include_edge_cases: test_code += f''' test('edge cases', () => {{ // TODO: implement edge case tests }}); ''' if include_mocks: test_code += f''' test('with mocks', () => {{ // TODO: implement tests with mocks }}); ''' test_code += '});\n' return test_code
bash
python
examples/test_generator_example.py
from skills.test_generator import TestGeneratorSkill from claude_code_sdk import SkillContext
创建 Skill 实例
skill = TestGeneratorSkill() context = SkillContext()
示例 1:生成 pytest 测试
result = skill.execute( { "file_path": "src/utils.py", "test_framework": "pytest", "include_edge_cases": True, "include_mocks": False }, context )
print(result.data["test_code"])
示例 2:生成 unittest 测试
result = skill.execute( { "file_path": "src/utils.py", "test_framework": "unittest" }, context )
print(result.data["test_code"])
示例 3:生成 Jest 测试
result = skill.execute( { "file_path": "src/utils.js", "test_framework": "jest" }, context )
print(result.data["test_code"])
bash